// shopMallPackage/pages/exchangeActivity/exchangeActivity.js
import { queryStoreDetail, getAddressDefault, getMyWallet, getReceiveAddressDetail, shopBuyRequest, mallBuyRequest } from "../../../service/onetoone_service"
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    formData: {
      addressId: null,
      payType: 1,
      cartIds: [],
    },
    detailId: null,
    mealId: null,

    mealData: {},//套餐内容
    payType: 1,// 1: 积分支付 2:微信支付
    houseDetail: {},
    addressData: { realName: "" },//默认地址
    balanceMoney: 0,
    addressId: null,// 选中的收货地址id
    isShowScorePay: true,
    cartList: [],
    totalMoney: 0,
    postage: 0,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {


    this.setData({
      cartList: app.globalData.cartList,
      totalMoney: app.globalData.cartMoney,
    })
    // 计算邮费:
    this.settlePostage();

    this.getAddressDefault();
    this.myWalletInfo();
    setTimeout(() => {
      this.selectPayType();
    }, 1500)

  },

  selectPayType() {
    if (this.data.balanceMoney < (this.data.totalMoney + this.data.postage)) {
      this.setData({
        isShowScorePay: false,
        "formData.payType": 2,
        payType: 2,
      })
    }
  },
  // 计算邮费;
  settlePostage() {
    let arr = [];
    // cardIds计算:
    let ids = [];
    this.data.cartList.forEach((item) => {
      arr.push(item.postage)
      ids.push(item.id)
    })
    let postage = arr.reduce((num1, num2) => {
      return num1 > num2 ? num1 : num2
    }
    )
    this.setData({
      postage: postage,
      'formData.cartIds': ids
    })



  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (app.globalData.selectAddressId) {
      this.setData({
        addressId: app.globalData.selectAddressId
      })
      app.globalData.selectAddressId = null;
      this.getReceiveAddressDetail();
    }
  },
  getReceiveAddressDetail() {
    wx.showLoading();
    getReceiveAddressDetail(this.data.addressId).then(res => {
      console.log("JJLog:收货地址详情===:" + JSON.stringify(res));
      wx.hideLoading();
      if (res.code == 200) {
        this.setData({
          addressData: res.data,
          'formData.addressId': res.data.id,
        })
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || "查询失败",
        icon: "none"
      })
      console.error("JJLog:getReceiveAddressDetail", err);
    })
  },

  //获取我的积分数据:
  myWalletInfo() {
    getMyWallet().then(res => {
      console.log("JJLog:钱包数据===:" + JSON.stringify(res));
      if (res.code == 200) {
        this.setData({
          balanceMoney: res.data.restMoney || 0,
        })
      }
    }).catch(err => {
      console.error("JJLog:getMyWallet", err);
    })
  },
  payTypeChange(e) {
    let index = e.currentTarget.dataset.index;
    if (!this.data.isShowScorePay && index == 1) {
      wx.showToast({
        title: '您的积分不足以购买此商品',
        icon: "none"
      })
      return;
    }
    this.setData({
      payType: index,
      'formData.payType': index,
    })
  },
  //查询商品详情:
  queryStoreDetail() {
    wx.showLoading({
      title: '加载中...',
    })
    queryStoreDetail(this.data.detailId).then(res => {
      wx.hideLoading();
      console.log("JJLog:商品详情是:" + JSON.stringify(res));
      if (res.code == 200) {
        this.setData({
          houseDetail: res.data
        })
        // this.dealMealMoneyShow(res.data);
      }
    }).catch(err => {

      console.error("JJLog:queryStoreDetail:", err);
      wx.hideLoading();
      wx.showToast({
        title: err || "详情获取失败",
        icon: "none"
      })
      setTimeout(() => {
        wx.navigateBack({
          delta: 0,
        })
      }, 2000);
    })
  },
  dealMealMoneyShow(data) {
    // let items = data.items;

  },
  getAddressDefault() {
    getAddressDefault().then(res => {
      console.log("JJLog:默认地址是:" + JSON.stringify(res));
      if (res.code == 200) {
        this.setData({
          addressData: res.data,
        })
        if (this.data.addressData.id) {
          this.setData({
            'formData.addressId': this.data.addressData.id,
          })
        }
      }
    }).catch(err => {
      console.error("JJLog:getAddressDefault:", err);
    })
  },
  // 去选择收货地址
  pushToSelectAddress() {
    wx.navigateTo({
      url: '/shopMallPackage/pages/addressList/addressList?isSelect=1',
    })
  },

  surePayAction() {
    if (!this.data.formData.addressId) {
      wx.showToast({
        title: '请选择收货地址',
        icon: "none"
      })
      return;
    }

    wx.showLoading({
      title: '支付中...',
    })

    mallBuyRequest(this.data.formData).then(res => {
      console.log("JJLog:支付回调:" + JSON.stringify(res));
      if (res.code == 200) {
        if (this.data.payType == 1 || res.data.isFree) {
          wx.hideLoading();
          // wx.navigateTo({
          //   url: '/storePackage/pages/exchangeSuccess/exchangeSuccess',
          // })
          // return;
          wx.showToast({
            title: '购买成功',
            icon: "success"
          })
          setTimeout(() => {
            wx.redirectTo({
              url: '/shopMallPackage/pages/myOrderList/myOrderList',
            })
          }, 2000)
          return;
        }
        console.log("JJLog:这里没来")
        let payData = res.data.data;
        wx.requestPayment({
          timeStamp: payData.timeStamp,
          nonceStr: payData.nonceStr,
          package: payData.packageValue,
          signType: 'MD5',
          paySign: payData.paySign,
          success: (res) => {
            wx.hideLoading();
            console.log("JJLog:微信支付成功回调:" + JSON.stringify(res));
            wx.showToast({
              title: '支付成功',
              icon: "success",
              duration: 2000
            })
            setTimeout(() => {
              // wx.navigateTo({
              //   url: '/storePackage/pages/exchangeSuccess/exchangeSuccess',
              // })
              wx.navigateBack({
                delta: 0,
              })
            }, 2000);

          },
          fail: (err) => {
            wx.hideLoading();
            wx.showToast({
              title: '支付失败',
              icon: "none"
            })
            console.log("JJLog:微信支付失败回调:" + JSON.stringify(err));
          }
        });
      }
    }).catch(err => {
      console.error("JJLog购买商品失败:" + JSON.stringify(err));
      wx.hideLoading();
      wx.showToast({
        title: err || "操作失败",
        icon: "none"
      })
    })
  },



})